package com.javalong.mir.dwz.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javalong.mir.constant.Constant;
import com.javalong.mir.constant.StatusCode;
import com.javalong.mir.dwz.vo.DwzResponse;
import com.javalong.mir.pojo.User;
import com.javalong.mir.service.UserService;

@Controller
@RequestMapping("dwz/user")
public class DwzUserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("list")
	public String list(Model model) {
		List<User> userList = userService.getList(0, Constant.PAGE_SIZE);
		model.addAttribute(userList);
		model.addAttribute("totalCount", userService.getCount());
		model.addAttribute("currentPage", 1);
		model.addAttribute("numPerPage", Constant.PAGE_SIZE);
		return "user/list";
	}

	@RequestMapping("listByPage")
	public String listByPage(@RequestParam("pageNum") int pageNum, @RequestParam("numPerPage") int numPerPage,
			Model model) {
		List<User> userList = userService.getList(pageNum - 1, numPerPage);
		model.addAttribute(userList);
		model.addAttribute("totalCount", userService.getCount());
		model.addAttribute("currentPage", pageNum);
		model.addAttribute("numPerPage", numPerPage);
		return "user/list";
	}

	@RequestMapping("delete")
	@ResponseBody
	public DwzResponse delete(@RequestParam("id") int id) {
		userService.delete(id);
		DwzResponse response = new DwzResponse();
		response.setStatusCode(StatusCode.SUCCESS);
		response.setMessage("删除成功!");
		response.setNavTabId("user_list");
		return response;
	}

	@RequestMapping("addjsp")
	public String addjsp() {
		return "user/add";
	}

	@RequestMapping("add")
	@ResponseBody
	public DwzResponse add(User user) {
		userService.save(user);
		DwzResponse response = new DwzResponse();
		response.setStatusCode(StatusCode.SUCCESS);
		response.setMessage("添加成功!");
		response.setNavTabId("user_list");
		response.setCallbackType("closeCurrent");
		return response;
	}

	@RequestMapping("updatejsp")
	public String updatejsp(@RequestParam("id")int id,Model model) {
		User user = userService.findUserById(id);
		if(user!=null){
			model.addAttribute(user);
		}
		return "user/update";
	}

	@RequestMapping("update")
	@ResponseBody
	public DwzResponse update(User user) {
		userService.updateUser(user);
		DwzResponse response = new DwzResponse();
		response.setStatusCode(StatusCode.SUCCESS);
		response.setMessage("更新成功!");
		response.setNavTabId("user_list");
		response.setCallbackType("closeCurrent");
		return response;
	}


}
